<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800">
    <el-alert type="success"
      >数字云渠道的审批单会自动调用主叫加白审批API接口，其他渠道的审批单请人工报送至三方审批并确认审批通过。</el-alert
    >

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="审批名称" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="2">通过</el-radio>
          <el-radio :label="99">拒绝</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="原因描述" prop="result">
        <el-input
          v-model="formData.result"
          placeholder="请输入原因描述"
          type="textarea"
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as WhiteAuditApi from '@/api/system/whiteaudit'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  status: undefined,
  result: undefined
})
const formRules = reactive({
  status: [
    {
      required: true,
      message: '审批结果不能为空',
      trigger: 'blur'
    }
  ],
  result: [
    {
      required: true,
      message: '原因描述不能为空',
      trigger: 'blur'
    }
  ]
})

const formRef = ref() // 表单 Ref
/** 打开弹窗 */
const open = async (id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = '审批'
  resetForm()
  formData.value.id = id
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    await WhiteAuditApi.submitReview(formData.value)
    message.success('审批成功！')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    status: undefined,
    result: undefined
  }
  formRef.value?.resetFields()
}
</script>
<style lang="scss" scope>
::v-deep(.el-range-editor.el-input__wrapper) {
  width: 200px !important;
}
</style>
